package com.njworkorder.Controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njworkorder.DTO.MonthExamineDto;
import com.njworkorder.Entity.*;
import com.njworkorder.Service.MeSectionService;
import com.njworkorder.VO.MonthExamineVO;
import com.njworkorder.Mapper.MonthExamineMapper;
import com.njworkorder.Service.MonthExamineService;
import com.njworkorder.Utils.Result;
import com.njworkorder.Utils.ResultUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Tag(name = "月度考核相关接口", description = "月度考核相关接口")
@RestController
@RequestMapping("/mon")
public class MonthExamineController {

    private final MonthExamineService monthExamineService;
    private final MeSectionService meSectionService;
    public MonthExamineController(MonthExamineService monthExamineService,
                                  MeSectionService meSectionService) {
        this.monthExamineService = monthExamineService;
        this.meSectionService = meSectionService;
    }

    @Operation(summary = "根据id删除月度考核")
    @GetMapping("/deleteAnId")
    public Result<String> deleteMetId(@RequestParam("id") String id){
        boolean removeById = monthExamineService.removeById(id);
        if (removeById){
            LambdaQueryWrapper<MeSection> queryWrapper = new LambdaQueryWrapper<MeSection>()
                    .eq(MeSection::getMeId, id);
            meSectionService.remove(queryWrapper);

            return ResultUtil.success("删除成功");
        }
        return ResultUtil.error("删除失败");
    }

    @Transactional
    @Operation(summary = "根据id修改月度考核")
    @PostMapping("/updateAnId/{id}")
    public Result<String> updateManId(@RequestBody MonthExamineDto meteringInventoryDTO,
                                      @PathVariable("id") String id){
        MonthExamine Met = new MonthExamine();
        Met.setId(id);

        BeanUtils.copyProperties(meteringInventoryDTO, Met);

        boolean b = monthExamineService.updateById(Met);
        if (b){
            LambdaQueryWrapper<MeSection> queryWrapper = new LambdaQueryWrapper<MeSection>()
                    .eq(MeSection::getMeId, id);
            meSectionService.remove(queryWrapper);

            addMESectionIfo(id,meteringInventoryDTO.getSectionId());

            return ResultUtil.success("修改成功");
        }
        return ResultUtil.fail("修改失败");
    }

    @Operation(summary = "获取月度考核列表")
    @GetMapping("/getParentIdList")
    public Result<Page<MonthExamineVO>> getMonListTree(@RequestParam(value = "unitAoId",required = false) String unitAoId,
                                                       @RequestParam(value = "sectionId",required = false) String sectionId,
                                                       @RequestParam(value = "workspaceId",required = false) String workspaceId,
                                                       @RequestParam("pageIndex") int pageIndex,
                                                       @RequestParam("pageSize") int pageSize) {

        MPJLambdaWrapper<MonthExamine> wrapper = new MPJLambdaWrapper<MonthExamine>()
                .selectAll(MonthExamine.class)
                .selectAs("GROUP_CONCAT(t3.section_name SEPARATOR ',')",MonthExamineVO::getSectionName)
                .selectAs("GROUP_CONCAT(t3.id SEPARATOR ',')",MonthExamineVO::getSectionId)

                .leftJoin(AdministrativeOrganization.class,AdministrativeOrganization::getId,MonthExamine::getUnitAoId, ext ->
                        ext.selectAs(AdministrativeOrganization::getName, MonthExamineVO::getUnitAoName))
                .leftJoin(MeSection.class,MeSection::getMeId,MonthExamine::getId)
                .leftJoin(Section.class,Section::getId,MeSection::getSectionId)
                .leftJoin(Workspace.class,Workspace::getId,MonthExamine::getWorkspaceId,ext ->
                        ext.selectAs(Workspace::getWorkspaceName, MonthExamineVO::getWorkspaceName))

                .groupBy(MonthExamine::getId)
                .orderByDesc(MonthExamine::getEndYear,MonthExamine::getEndMonth,MonthExamine::getEndDay)
                .apply("1=1")
                .eq(StringUtils.isNotEmpty(unitAoId), MonthExamine::getUnitAoId, unitAoId)
                .eq(StringUtils.isNotEmpty(workspaceId), MonthExamine::getWorkspaceId, workspaceId)
                .eq(StringUtils.isNotEmpty(sectionId),MeSection::getSectionId, sectionId);

        Page<MonthExamineVO> monthExamineVOPage = monthExamineService.selectJoinListPage(new Page<>(pageIndex, pageSize), MonthExamineVO.class, wrapper);
        return ResultUtil.success(monthExamineVOPage);
    }

    @Transactional
    @Operation(summary = "新增月度考核")
    @PostMapping("/MonInfo")
    public Result<String> addInfo(@RequestBody MonthExamineDto monthExamineDto,
                                  @RequestHeader("Create-Ap-Id") String createApId){

        MonthExamine Mo = new MonthExamine();
        BeanUtils.copyProperties(monthExamineDto,Mo);
        String id = UUID.randomUUID().toString();
        Mo.setId(id);
        Mo.setCreateApId(createApId);

        boolean save = monthExamineService.save(Mo);
        if (save){
            addMESectionIfo(id,monthExamineDto.getSectionId());
            return ResultUtil.success("添加成功");
        }
        return ResultUtil.fail("添加失败");
    }

    @Operation(summary = "获取季度综合考核得分")
    @GetMapping("/getQCAScore")
    public Result<Map<String,String>> getQCAScore(){

        LambdaQueryWrapper<MonthExamine> wrapper = new LambdaQueryWrapper<MonthExamine>()
                .select(MonthExamine::getAmount)
                .eq(MonthExamine::getAssCycle,2)
                .orderByDesc(MonthExamine::getPublishTime)
                .last("limit 1");
        MonthExamine one = monthExamineService.getOne(wrapper);

        Map<String,String> map = new HashMap<>();
        map.put("score", one == null ? "0" : String.valueOf( one.getAmount()));

        return ResultUtil.success(map);
    }

    private void addMESectionIfo(String meId, List<String> sectionIds){
        if (sectionIds == null || sectionIds.isEmpty()){
            return;
        }
        List<MeSection> meSectionList = new ArrayList<>();
        MeSection  meSection;
        for (String sectionId : sectionIds){
            meSection = new MeSection();
            meSection.setMeId(meId);
            meSection.setSectionId(sectionId);
            meSectionList.add(meSection);
        }
        meSectionService.saveBatch(meSectionList);
    }

}
